#include <stx/imp/cmn.hpp>

inline namespace stx
{
bool isNaturalNumber(std::string_view const sv)
{
    return isMatch(sv, rgx<R"(^(0|[1-9][0-9]*)$)">());
}

bool isIp4(std::string_view const sv)
{
    // clang-format off
    return isMatch(sv, rgx<
R"(^((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.))"
R"({3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])$)">());
    // clang-format on
}

bool isIp6(std::string_view const sv)
{
    // clang-format off
    return isMatch(sv, rgx<
R"(^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|)"
R"(([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|)"
R"(([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|)"
R"(([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|)"
R"(([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|)"
R"(([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|)"
R"([0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|)"
R"(:((:[0-9a-fA-F]{1,4}){1,7}|:)|)"
R"(fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|)"
R"(::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|)"
R"(1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|)"
R"(1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4})"
R"(:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3})"
R"((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$)">());
    // clang-format on
}

bool isIpPort(std::string_view const sv)
{
    auto mr = getMatchResults(sv, rgx<R"((.+):([0-9]|[1-9][0-9]*))">());
    if (mr.size() != 3)
    {
        return false;
    }

    auto sv_ip = mr[1];
    if (sv_ip.size() < 2)
    {
        return false;
    }

    if ('[' == sv_ip.front())
    {
        sv_ip = tosv(sv_ip.data() + 1, sv_ip.size() - 2);
    }

    if (!isIp4(sv_ip) && !isIp6(sv_ip))
    {
        return false;
    }

    auto const sv_port = mr[2];
    if (sv_port.size() > 5)
    {
        return false;
    }

    auto const opt = ton(sv_port);
    return opt && *opt <= max<std::uint16_t>();
}
} // namespace stx